package ljl.alg.jianzhioffer.round3.medium;

public class _36_treeToDoublyList {
    static class Node {
        public int val;
        public Node left;
        public Node right;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val,Node _left,Node _right) {
            val = _val;
            left = _left;
            right = _right;
        }
    };


    public Node treeToDoublyList(Node root) {
        if (root == null) return null;
        inorder(root);
        head.left = prev;
        prev.right = head;
        return head;
    }
    Node prev;
    Node head;
    void inorder(Node root) {
        if (root == null) return;
        inorder(root.left);
        if (prev != null) {
            prev.right = root;
            root.left = prev;
        } else
            head = root;
        prev = root;
        inorder(root.right);
    }

}
